package com.jsh.erp.service.flow;

import com.jsh.erp.dao.mappers.FlowLogMapper;
import com.jsh.erp.dao.mappers.FlowMapper;
import com.jsh.erp.dao.mappers.FlowMapperEx;
import com.jsh.erp.domain.entities.Flow;
import com.jsh.erp.domain.entities.FlowExample;
import com.jsh.erp.domain.entities.FlowLog;
import com.jsh.erp.domain.entities.FlowLogExample;
import com.jsh.erp.service.log.LogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class FlowService {

    private Logger logger = LoggerFactory.getLogger(FlowService.class);

    @Resource
    private FlowMapper flowMapper;

    @Resource
    private FlowMapperEx flowMapperEx;

    @Resource
    private FlowLogMapper flowLogMapper;
    @Resource
    private LogService logService;

    //根据流程名称查询流程第一个节点
    public Flow getFirstByName(String flowName) {
        FlowExample flowExample = new FlowExample();
        flowExample.createCriteria().andNameEqualTo(flowName).andDeleteFlagNotEqualTo(1);
        flowExample.setOrderByClause("sort ASC");
        List<Flow> flows = flowMapper.selectByExample(flowExample);
        if (CollectionUtils.isEmpty(flows)) {
            return new Flow();
        }
        return flows.get(0);
    }

    public List<Flow> getByName(String flowName) {
        FlowExample flowExample = new FlowExample();
        flowExample.createCriteria().andNameEqualTo(flowName).andDeleteFlagNotEqualTo(1);
        flowExample.setOrderByClause("sort ASC");
        List<Flow> flows = flowMapper.selectByExample(flowExample);
        if (CollectionUtils.isEmpty(flows)) {
            return new ArrayList<>();
        }
        return flows;
    }

    public Flow getNextByFlowId(Long flowId) {
        return flowMapperEx.getNextBydFlowId(flowId);
    }

    public Flow getById(Long flowId) {
        return flowMapper.selectByPrimaryKey(flowId);
    }

    public List<Flow> list() {
        return flowMapper.selectByExample(new FlowExample());
    }

    public int insertFlowLog(FlowLog flowLog) {
        return flowLogMapper.insertSelective(flowLog);
    }

    public List<FlowLog> getFlowLogByBillNo(String billNo) {
        FlowLogExample flowLogExample = new FlowLogExample();
        flowLogExample.createCriteria().andBillNoEqualTo(billNo);
        return flowLogMapper.selectByExample(flowLogExample);
    }

    public List<Long> getFlowLogIdsByBillNo(String billNo) {
        FlowLogExample flowLogExample = new FlowLogExample();
        flowLogExample.createCriteria().andBillNoEqualTo(billNo).andIsAdminEqualTo(0);
        flowLogExample.setDistinct(true);
        return flowLogMapper.selectIdByExample(flowLogExample);
    }
}
